#!/bin/bash
PKGNAME="Wiizard"
VERSION="0.1-alpha1"
REL=1
ARCH="amd64"
MAINTAINER="CYBERDEViL <cyberdevil@notabug.org>"
DESC="A Wii games manager"
URL="https://notabug.org/cyberdevil/Wiizard"
MAKEDEPENDS=("git" "build-essential" "libssl-dev" "libtinfo-dev" "zlib1g-dev"
             "libncurses-dev" "python3-distutils" "python3-dev" "libfdisk-dev"
             "libblkid-dev")
DEPENDS=("openssl" "libc6" "libmhash2" "libbz2-1.0" "zlib1g" "python3-requests"
         "python3-pyudev" "python3-bs4" "python3-lxml" "python3-pyqt5")


SRCDIR=$(realpath "${PKGNAME}")
PKGDIR=$(realpath "${PKGNAME}-${VERSION}-${REL}_${ARCH}")


check_deps() {
  MISSING=()
  for pkg in "${MAKEDEPENDS[@]}"; do
    dpkg -s "${pkg}" > /dev/null 2>&1
    if [[ $? -ne 0 ]]; then
      echo " - '${pkg}'"
      MISSING+=("${pkg}")
    fi
  done

  for pkg in "${DEPENDS[@]}"; do
    dpkg -s "${pkg}" > /dev/null 2>&1
    if [[ $? -ne 0 ]]; then
      MISSING+=("${pkg}")
    fi
  done

  if [[ ${#MISSING[@]} -ne 0 ]]; then
    echo "The following packages are missing, please install them first:"
    echo ""
    echo "  ${MISSING[@]}"
    echo ""
    exit 1
  fi
}


get_sources() {
  if [[ ! -d "${PKGNAME}" ]]; then
    git clone --recurse-submodules "${URL}" "${PKGNAME}"
  fi
}

prepare() {
  sed 's/\/usr\/share\//\/usr\/local\/share\//' -i "${PKGNAME}/share/Wiizard.desktop"
}

build() {
  cd "${SRCDIR}"
  make bundle
}

package() {
  cd "${SRCDIR}"
  make DESTDIR="${PKGDIR}/" PREFIX="usr/" install
}


# Check dependencies
check_deps


# Make sure the pkg dir is fresh
if [[ -d "${PKGDIR}" ]]; then
  rm -rf "${PKGDIR}"
fi
mkdir "${PKGDIR}"

# Get the sources
get_sources

# Prepare
prepare

# Build the sources
build

# Package
package


mkdir "${PKGDIR}/DEBIAN"
echo "Package: ${PKGNAME}
Version: ${VERSION}
Maintainer: ${MAINTAINER}
Depends: ${DEPENDS}
Architecture: ${ARCH}
Homepage: ${URL}
Description: ${DESC}" \
> "${PKGDIR}/DEBIAN/control"

dpkg --build "${PKGDIR}"
